<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Chongqingjiyu extends AbstractApi
{
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key)
    {
        ksort($array);
        $signStr = $secret_key;
        foreach ($array as $k => $v) {
            $signStr .= $k . $v;
        }
        return strtolower(md5($signStr));
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $data = [
            'customer_id'       => $bean->getSupplierNum(),
            'timestamp'         => time(),
            'product_id'        => $bean->getGoodsId(),
            'recharge_account'  => $bean->getAccount(),
            'quantity'          => $bean->getRechargeNum() * $bean->getStartCharging(), //充值数量
            'notify_url'        => $bean->getNotifyUrl(),
            'outer_order_id'    => $bean->getOrderNo(),//订单号
            'safe_cost'         => $bean->getUnitPrice(),
            'client_ip'         => $bean->getIp(),
        ];
        $data['sign'] = $this->sign($data, $bean->getSecretKey());
        return $data;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('state', '');
        $order_sn = $request->input('outer_order_id', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['200', '500']))->setRechargeSuccess($status == '200');
    }

    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response('success');
    }
}
